import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:mobpush_plugin/mobpush_notify_message.dart';
import 'package:mobpush_plugin/mobpush_plugin.dart';



import 'package:permission_handler/permission_handler.dart';
// import 'package:rtckit/rtckit.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:mobcommonlib/mobcommonlib.dart';

import 'package:sph_shipper/l10n/locales/en.dart' as en;
import 'package:sph_shipper/l10n/locales/zh.dart' as zh;

import 'dart:io' show Platform;
import 'Login/GuidePage.dart';
import 'TabBar/TabbarView.dart';
import 'l10n/messages.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart'
    show BMFMapSDK, BMF_COORD_TYPE;
// import 'package:mobpush_plugin/mobpush_plugin.dart';
import 'package:mobpush_plugin/mobpush_custom_message.dart';
// import 'package:mobpush_plugin/mobpush_notify_message.dart';
void main()async {
  // runApp(const MyApp());
  WidgetsFlutterBinding.ensureInitialized(); //必须要添加这个进行初始化 否则下面会错误
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp])
      .then((_) {
    runApp(const MyApp());
  });
  LocationFlutterPlugin myLocPlugin = LocationFlutterPlugin();
  // 设置是否隐私政策
  myLocPlugin.setAgreePrivacy(true);

  BMFMapSDK.setAgreePrivacy(true);
  // WidgetsFlutterBinding.ensureInitialized();
  // await SharedPreferences.getInstance();
  if (Platform.isIOS) {
    /// 设置ios端ak, android端ak可以直接在清单文件中配置
    myLocPlugin.authAK('576q3hliqW2s0zEEq5XATUlzDCoVOROT');
    //设置远程推送环境，向用户授权 开发环境 false, 线上环境 true
    MobpushPlugin.setAPNsForProduction(false);
  }
  else if (Platform.isAndroid) {

    /// 初始化获取Android 系统版本号，如果低于10使用TextureMapView 等于大于10使用Mapview
    // await BMFAndroidVersion.initAndroidVersion();
    // Android 目前不支持接口设置Apikey,
    // 请在主工程的Manifest文件里设置，详细配置方法请参考官网(https://lbsyun.baidu.com/)demo
    BMFMapSDK.setCoordType(BMF_COORD_TYPE.BD09LL);
  }

}


class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  //setLocale 方法用于从应用的任何位置切换语言环境。它通过找到最近的 _MyAppState 实例，并调用其 setLocale 方法来实现切换语言功能。
  static void setLocale(BuildContext context, Locale newLocale) {
    _MyAppState state = context.findAncestorStateOfType<_MyAppState>()!;
    state.setLocale(newLocale);
  }

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {

  Future<void> _requestLocationPermission() async {
    final status = await Permission.location.request();
    if (status == PermissionStatus.granted) {
      // 定位权限已授予
    } else {
      // 用户拒绝了定位权限
      // 可以在这里做一些处理，例如提示用户手动授予权限
    }
  }

  Locale _locale = const Locale('zh', ''); // 默认语言为中文
//_loadLocaleFromPreferences 方法从 SharedPreferences 中加载用户偏好设置的语言环境。如果存在保存的语言代码，就将其更新到 _locale 变量中。
  Future<void> _loadLocaleFromPreferences() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? languageCode = prefs.getString('languageCode');
    if (languageCode != null) {
      setState(() {
        _locale = Locale(languageCode, '');
      });
    }
  }

//_saveLocaleToPreferences 方法用于将选择的语言环境保存到 SharedPreferences 中，以便下次启动应用时可以加载该语言环境。
  Future<void> _saveLocaleToPreferences(Locale locale) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('languageCode', locale.languageCode);
  }

  void setLocale(Locale newLocale) {
    _saveLocaleToPreferences(newLocale);
    setState(() {
      _locale = newLocale;
    });
  }
  String satoken="";
  String _sdkVersion = 'Unknown';
  String _registrationId = 'Unknown';
  // 上一次点击返回键的时间
  DateTime? lastPressed;
  @override
  void initState() {
    super.initState();
    _loadLocaleFromPreferences();
    _requestLocationPermission();
    // imInit();
    // getSaToken();
    MobpushPlugin.updatePrivacyPermissionStatus(true).then((value) {
      print(">>>>>>>>>>>>>>>>>>>updatePrivacyPermissionStatus:" +
          value.toString());
    });
    if (Platform.isIOS) {
      //设置地区：regionId 默认0（国内），1:海外
      MobpushPlugin.setRegionId(0);
      MobpushPlugin.registerApp("382cc026f7b99", "55ac806c6dedd96de7bcad8f1b1ad214");
    }
    initPlatformState();
    if (Platform.isIOS) {
      MobpushPlugin.setCustomNotification();
      MobpushPlugin.setAPNsForProduction(true);
    }
    MobpushPlugin.addPushReceiver(_onEvent, _onError);
  }

  Future<void> initPlatformState() async {
    String sdkVersion;
    try {
      sdkVersion = await MobpushPlugin.getSDKVersion();
    } on PlatformException {
      sdkVersion = 'Failed to get platform version.';
    }
    try {
      Future.delayed(Duration(milliseconds: 500), () {
        MobpushPlugin.getRegistrationId().then((Map<String, dynamic> ridMap) {
          print(ridMap);
          setState(() {
            _registrationId = ridMap['res'].toString();
            print('------>#### registrationId: ' + _registrationId);
          });
        });
      });
    } on PlatformException {
      _registrationId = 'Failed to get registrationId.';
    }
  }
  void _onEvent(dynamic event) {
    print('>>>>>>>>>>>>>>>>>>>>>>>>>>>onEvent:' + event.toString());
    setState(() {
      Map<String, dynamic> eventMap = json.decode(event as String);
      Map<String, dynamic> result = eventMap['result'];
      int action = eventMap['action'];

      switch (action) {
        case 0:
          MobPushCustomMessage message =
          new MobPushCustomMessage.fromJson(result);
          showDialog(
              context: context,
              builder: (context) {
                return AlertDialog(
                  content: Text(message.content),
                  actions: <Widget>[
                    TextButton(
                        onPressed: () {
                          Navigator.pop(context);
                        },
                        child: Text("确定")
                    )
                  ],
                );
              });
          break;
        case 1:
          MobPushNotifyMessage message =
          new MobPushNotifyMessage.fromJson(result);
          break;
        case 2:
          MobPushNotifyMessage message =
          new MobPushNotifyMessage.fromJson(result);
          break;
      }
    });
  }
  void _onError(dynamic event) {
    setState(() {
      print('>>>>>>>>>>>>>>>>>>>>>>>>>>>onError:' + event.toString());
    });
  }
//   // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return  WillPopScope(
        onWillPop: () async {
      print("再按一次退出");
      // 获取当前时间
      final now = DateTime.now();
      // 如果 lastPressed 为空或者间隔时间超过 2 秒，则更新 lastPressed 并提示用户
      if (lastPressed == null || now.difference(lastPressed!) > Duration(seconds: 2)) {
        lastPressed = now;
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('再按一次退出'),
            duration: Duration(seconds: 2),
          ),
        );
        return false; // 不退出
      }
      return true; // 退出应用
    },
    child:
    ScreenUtilInit(
      designSize: const Size(360, 690),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (context , child) {
        return CupertinoApp(
          localizationsDelegates: const [
            GlobalMaterialLocalizations.delegate,
            AppLocalizationsDelegate(),
            GlobalWidgetsLocalizations.delegate,
            GlobalCupertinoLocalizations.delegate,

          ],
          supportedLocales: [
            Locale('en'),
            Locale('zh'),
          ],
          locale: _locale,

          debugShowCheckedModeBanner: false,
          title: 'First Method',
          // You can use the library anywhere in the app even in theme

          builder: (context, child) =>
              MediaQuery(data: MediaQuery.of(context).copyWith(alwaysUse24HourFormat: true), child: child!),
          home: child,
        );
      },
      // child: satoken!=""? TabbarView(pateIndex: 0, ):LoginVC(),
        child:GuidePage(),

    )
    );
  }
}


